var j = jQuery.noConflict();
var DEBUG = true;

j.fn.extend({
	flash: function(time, callback){
		if (!time) time = 2000;
		this.css('background-color','#cc0').animate({backgroundColor:'white'},time, callback);
	},
	gray: function(){
		this.addClass('grayed');
	},
	ungray: function(){ //for some reason this doesn't work.
		this.removeClass('grayed');
	}
});


function modify_entry(form, action, onSuccess){
	var dataString = '&action=' + action;
	
	tinyMCE.triggerSave();
	//todo: tinyMCE for edited entries, then can re enable this line
	
	
	j(":input", form).filter(":not(button)").filter(":not(input:checkbox)").each(function(){
		$field = j(this);
		dataString += '&'+$field.attr('name')+"="+escape($field.val());
	});
	j("input:checkbox", form).each(function(){
		var checked = j(this).is(":checked") ? '1' : '0';
		var name = j(this).attr('name')
		dataString += '&'+name+"="+ checked ;
	});
	
	//default path is /manager, so this url works
	jQuery.ajax({
		type: "POST",
		url: "../assets/plugins/dataFrolic/df_modify_entry.php",
		data: dataString,
		success: onSuccess
	});
}

//half made and unused cuurrenty
function ajaxTab(tab_type, tab){
	if (tab_type == 'M2M'){
		jQuery.ajax({
			type: "GET",
			url: "../assets/plugins/dataFrolic/frolic_M2M.php",
			success: function(resp){
				j(tab).html(resp);
			}
		});
	}else{
		if (DEBUG) alert('invalid tab type: ' + tab_type);
	}
}

function print_error(errorstring, clearFirst, pluralName){
	if (!clearFirst){ var clearFirst = false;}
	if (clearFirst){
		j("#error_field_" + pluralName).show().html("<p>" + errorstring + "</p>");
	}else{
		j("#error_field_" + pluralName).show().append("<p>" + errorstring + "</p>");
	}
}

function hide_errors(){
	j("#error_field").html('').hide();
}

//table row class for edit entries table:
// this is given a jQuery element, and all it does is hope that the formatting is correct, and add and removew rows.
//all elements are considered jQuery objects unless mentioned otherwise
function df_O2M_table(table){
	this.table = table;
	
	this.addRow = function(id, rowData){
		var tr = '<tr class="clickable" title="'+id+'">'; // 
		for ( var i =0; i < rowData.length; i++ ) { //for some reason, using 'for i in rowData 'causes code barf.
			tr += rowData[i];
		}
		tr += '</tr>';
		
		table.append(tr); // tr is a string
		$tr = j("tr:last", table);
		$tr.hover(function(){
			$tr.addClass('clickablehover');
		},function(){
			$tr.removeClass('clickablehover');
		});
		$tr.flash();
	}
	
	this.addFullRow = function(row){		
		table.append(row); // tr is a string
		
		$tr = j("tr:last", table);
		$tr.hover(function(){
			$tr.addClass('clickablehover');
		},function(){
			$tr.removeClass('clickablehover');
		});
		$tr.flash();
	}
	
	this.removeRow = function(id){
		var tr = j("tr[title='"+ id +"']", table);
		tr.css('background-color','#cc0').fadeOut(300, function(){
				tr.remove();
		});  

	}
	
	this.modifyRow = function(id, rowData){
		var tr = j("tr[title='"+ id +"']", table);
		var i = 0;
		j("td",tr).each(function(){
			j(this).text(rowData[i]);
			i++;
		});
		tr.flash();
	}
	
	this.replaceRow = function(id, html){
		var tr = j("tr[title='"+ id +"']", table);
		tr.replaceWith(html).flash();
	}
}


function df_M2M_table(tableCurrent, tableOther, dataHolder){
	this.tableCurrent = tableCurrent;  //jq objects
	this.tableOther = tableOther;
	
	
	
	j('a.removeM2M', tableCurrent).live('click', function(e){
		moveRow(e.target.parentNode.parentNode, e.target, tableOther, dataHolder, 'down');
	});
	
	j('a.addM2M', tableOther).live('click', function(e){
		var row = e.target.parentNode.parentNode, a = e.target;
		
		otherFields = j(".additional_M2M_fields", dataHolder).html();
		if(otherFields.length > 0){  //other DBs are @SELECT linked:
			showMoreFieldsBox(row, a, tableCurrent, dataHolder, otherFields);
		}else{
			moveRow(row, a, tableCurrent, dataHolder, 'up');
		}
	});
	
	this.showMoreFieldsBox = function(row, a, toTable, dataHolder, fieldHtml){
		
		$box = j("<div id='moreFieldsBox' style='position: absolute; font-size: 1.5em; top: 100px; left: 100px; padding: 1em; width: 300px; height: 300px; z-index: 10; background-color: #f0f0f0; display: none;'>" + fieldHtml + "<button id='addM2Msecond'>Submit</button><button id='cancelM2Mtransaction'>Cancel</button></div>").appendTo(tableCurrent.parent()).fadeIn('fast');
		$mask = j("<div id='mask' class='modal_mask'></div>").appendTo(tableCurrent.parent());
		
		j("#addM2Msecond").click(function(){  
			var data = '';
			j('select', '#moreFieldsBox').each(function(){
				$this = j(this);
				data += '&' + $this.attr('id') + '=' + $this.val();
			});
			$box.fadeOut('fast').remove();
			moveRow(row, a, toTable, dataHolder, 'up', data); 
		});
		
		j("#cancelM2Mtransaction").click(function(){
			$box.fadeOut('fast').remove();
		});
		
	}
	
	this.moveRow = function(row, a, toTable, dataHolder, direction, moreData){
		
		var $row = j(row), $a = j(a), id = $a.attr('title');
		var toText, toClass, onSuccess, onFail, data;
		$row.gray();
		
		var table_info = '&table_info=' + j('.M2M_info', dataHolder).val(),
			current_doc_id = '&current_doc_id=' + j('.current_doc_id', dataHolder).val();
		
		if (direction == 'up'){
			action = "add";
			// toTable = tableCurrent;
			toClass = "removeM2M";
			toText = "Remove From Current";
		}else if (direction == 'down'){
			action = "remove";
			// toTable = tableOther;
			toClass = "addM2M";
			toText = "Add to Current";
			//include all the table data, everything to describe the new M2M entry
		}else{
			return;
		}

		
		onSuccess = function(resp){ //todo add check
			$row.removeClass('grayed').remove().appendTo(toTable).flash(1000, function(){});
			$a.removeClass().addClass(toClass).text(toText);
		}
		
		//todo: learn more about error handling, and these objects.
		onFail = function(XMLHttpRequest, textStatus, errorThrown){
			$row.ungray();
			alert('error moving row status: ' + XMLHttpRequest.status);
			// console.log('error moving row status: ' + XMLHttpRequest.status);
		}
		
		
		var dataString = "&action=" + action + "&id=" + id + table_info + current_doc_id;
		if (!(moreData === undefined)) {dataString += moreData;}
		j.ajax({
			type: "POST",
			url: "../assets/plugins/dataFrolic/df_move_row.php",
			data: dataString,
			success: onSuccess,
			error: onFail
		});
	}
}

j(function(){  // on ready..
	myURL = parseURL(window.location);
	tab = myURL.params['tab'];
	if (!(tab === undefined)){
		try{
			tpSettings.setSelectedIndex( tab );
		}catch(err){
			//who cares ;-)
		}
	}
	

});

function df_filterbox(itemsName){
	
	j("#cancel_filter_" + itemsName).click(function(e){
		j("#filterbox_" + itemsName).val('');
		j("#df_other_" + itemsName + " tr").each(function(){
			j(this).show();
		});		
	});

	j("#filterbox_" + itemsName).keyup(function(e){
		var search = j(this).val();
		
		if (search == ''){
			j("#df_other_"+ itemsName +" tr").each(function(){
				j(this).show();
			});
			
		}else{
			var title, $row;
			var searchRegex = new RegExp(search, 'i'); 
			j("#df_other_"+ itemsName +" tr:gt(0)").each(function(){  //skip header row
				$row = j(this);
				title = j("td:eq(0)", this).html();
				if ( title.search(searchRegex) < 0 ){
					$row.hide();
				}else{
					$row.show();
				}
			});
		}
		
	});
} 

j(function($){

	// edit box functions:
	//cancel the edit:
	j("#editentry_close").click(function(e){
		e.preventDefault();
		modal.hide();
	});

	//delete an entry:
	j("#editentry_delete").click(function(e){
		e.preventDefault();
		if ((confirm('Really Destoy Record?'))){	
			var plural_name = j('#plural_name', '#editentry_form').html();
			modify_entry('#editentry_form', 'destroy', function(resp){
				if (resp == '200'){
					power_table.removeRow(entry_id);
				}else{
					print_error('database error: ' + resp);
				}
			});
			modal.hide();
		}
	});



	j("#editentry_save").click(function(e){
		e.preventDefault();
		$form = j("#editentry_form");
		
		var rowData = new Array();
		
		$form.append('<br>Saving entry... <br>');

		modify_entry($form, 'update', function(resp){
			resp = eval('('+ resp +')');
			if (resp.status == '200'){
				power_table.replaceRow(resp.id, resp.rowData);
				j("#editentry_form").html('Entry Saved');
			
				modal.hide();
			}else{ //error
			}
		});
	
		return false;
	});
	
}); //end on dom ready


function launch_img_uploader(){
	var ajax_window = window.open("../assets/plugins/dataFrolic/img_uploader.php", 'ajax_window');
	j(window).unload(function(){
		ajax_window.close();
	});
}

function launch_attachment_uploader(){
	var ajax_window = window.open("../assets/plugins/dataFrolic/attachment_uploader.php", 'ajax_window');
	j(window).unload(function(){
		ajax_window.close();
	});
}

function clear_newEntry_form(){
	if (j("#attachments_display").length !== 0){
		j("#attachments_display").html('');
		j("#attachments_field").val('');
	}
	if (j("#uploaded_img_display").length !== 0){
		j("#uploaded_img_display").html('');
		j("#uploaded_img_field").val('');
	}
}


//modal helper functions:
function modal_window(box_id){
	this.$box = j("#" + box_id);
	
	j('#mask').click(function(){
		$box.hide();
	})
	
	this.center = function(){
		// var window_width = j(window).width();
		// var window_height = j(window).height();
		// var width = this.$box.outerHeight();
		// var height = this.$box.outerWidth();
		
		// var top = (window_height - height) /2;
		// var left = (window_width - width) /2;
		
		if (window.pageYOffset){
			var scrollY = window.pageYOffset;
		}else{
			var scrollY = document.documentElement.scrollTop;
		}
		
		
		// this.$box.css({'top' : top, 'left' : left});
		this.$box.css({'top' : scrollY + 50, 'left' : "50px"});
	}
	
	this.show = function(){
		 this.center();
		j('#modal_mask').css({ 'display' : 'block', opacity : 0}).fadeTo(500, 0.8);
		 this.$box.fadeIn(500); 
	}
	
	this.hide = function(){
		j("#modal_mask").fadeOut(500);
		this.$box.fadeOut(500);
	}
	
	this.html = function(content){
		this.$box.html(content);
	}
	
	this.append = function(content){
		this.$box.append(content);
	}
}


// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).
 //http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}
